using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.Enums;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Write.Controllers;

/// <summary>
/// 开单申请控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class OrderApplicationController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<OrderApplicationController> _logger;

    public OrderApplicationController(IMediator mediator, ILogger<OrderApplicationController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// 提交开单申请
    /// </summary>
    /// <param name="command">开单申请命令</param>
    /// <returns>申请结果</returns>
    [HttpPost("submit")]
    [ProducesResponseType(typeof(APIResult<OrderApplicationResultDto>), 200)]
    public async Task<ActionResult<APIResult<OrderApplicationResultDto>>> SubmitOrderApplication(
        [FromBody] SubmitOrderApplicationCommand command)
    {
        try
        {
            _logger.LogInformation("接收到开单申请提交请求，用户ID：{UserId}，院区ID：{HospitalAreaId}，项目数量：{ItemCount}", 
                command.UserId, command.HospitalAreaId, command.Items?.Count ?? 0);

            if (command == null)
            {
                _logger.LogWarning("开单申请命令为空");
                return Ok(new APIResult<OrderApplicationResultDto>
                {
                    Code = APIEnum.Fail,
                    Message = "请求参数不能为空",
                    Data = null
                });
            }

            var result = await _mediator.Send(command);

            if (result.Code == APIEnum.OK)
            {
                _logger.LogInformation("开单申请提交成功，申请编号：{ApplicationNumber}，总金额：{TotalAmount}", 
                    result.Data?.ApplicationNumber, result.Data?.TotalAmount);
            }
            else
            {
                _logger.LogWarning("开单申请提交失败：{Message}", result.Message);
            }

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "提交开单申请时发生异常，用户ID：{UserId}", command?.UserId);
            
            return Ok(new APIResult<OrderApplicationResultDto>
            {
                Code = APIEnum.Fail,
                Message = $"提交开单申请失败：{ex.Message}",
                Data = null
            });
        }
    }

    /// <summary>
    /// 批量提交开单申请（预留接口）
    /// </summary>
    /// <param name="commands">开单申请命令列表</param>
    /// <returns>申请结果列表</returns>
    [HttpPost("batch-submit")]
    [ProducesResponseType(typeof(APIResult<List<OrderApplicationResultDto>>), 200)]
    public async Task<ActionResult<APIResult<List<OrderApplicationResultDto>>>> BatchSubmitOrderApplications(
        [FromBody] List<SubmitOrderApplicationCommand> commands)
    {
        try
        {
            _logger.LogInformation("接收到批量开单申请提交请求，申请数量：{Count}", commands?.Count ?? 0);

            if (commands == null || !commands.Any())
            {
                _logger.LogWarning("批量开单申请命令列表为空");
                return Ok(new APIResult<List<OrderApplicationResultDto>>
                {
                    Code = APIEnum.Fail,
                    Message = "请求参数不能为空",
                    Data = new List<OrderApplicationResultDto>()
                });
            }

            var results = new List<OrderApplicationResultDto>();
            var successCount = 0;
            var failCount = 0;

            foreach (var command in commands)
            {
                try
                {
                    var result = await _mediator.Send(command);
                    if (result.Code == APIEnum.OK && result.Data != null)
                    {
                        results.Add(result.Data);
                        successCount++;
                    }
                    else
                    {
                        failCount++;
                        _logger.LogWarning("批量申请中的单个申请失败，用户ID：{UserId}，错误：{Message}", 
                            command.UserId, result.Message);
                    }
                }
                catch (Exception ex)
                {
                    failCount++;
                    _logger.LogError(ex, "批量申请中的单个申请处理异常，用户ID：{UserId}", command.UserId);
                }
            }

            _logger.LogInformation("批量开单申请处理完成，成功：{SuccessCount}，失败：{FailCount}", successCount, failCount);

            return Ok(new APIResult<List<OrderApplicationResultDto>>
            {
                Code = successCount > 0 ? APIEnum.OK : APIEnum.Fail,
                Message = $"批量提交完成，成功：{successCount}，失败：{failCount}",
                Data = results
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量提交开单申请时发生异常");
            
            return Ok(new APIResult<List<OrderApplicationResultDto>>
            {
                Code = APIEnum.Fail,
                Message = $"批量提交开单申请失败：{ex.Message}",
                Data = new List<OrderApplicationResultDto>()
            });
        }
    }

    /// <summary>
    /// 支付开单申请
    /// </summary>
    /// <param name="command">支付命令</param>
    /// <returns>支付结果</returns>
    [HttpPost("pay")]
    [ProducesResponseType(typeof(APIResult<PaymentResultDto>), 200)]
    public async Task<ActionResult<APIResult<PaymentResultDto>>> PayOrderApplication(
        [FromBody] PayOrderApplicationCommand command)
    {
        try
        {
            _logger.LogInformation("接收到开单申请支付请求，申请ID：{OrderApplicationId}，用户ID：{UserId}，支付方式：{PaymentMethod}", 
                command.OrderApplicationId, command.UserId, command.PaymentMethod);

            if (command == null)
            {
                _logger.LogWarning("支付命令为空");
                return Ok(new APIResult<PaymentResultDto>
                {
                    Code = APIEnum.Fail,
                    Message = "请求参数不能为空",
                    Data = null
                });
            }

            var result = await _mediator.Send(command);

            if (result.Code == APIEnum.OK)
            {
                _logger.LogInformation("开单申请支付成功，申请ID：{OrderApplicationId}，交易号：{TransactionId}", 
                    command.OrderApplicationId, result.Data?.PaymentTransactionId);
            }
            else
            {
                _logger.LogWarning("开单申请支付失败：{Message}", result.Message);
            }

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理开单申请支付时发生异常，申请ID：{OrderApplicationId}", command?.OrderApplicationId);
            
            return Ok(new APIResult<PaymentResultDto>
            {
                Code = APIEnum.Fail,
                Message = $"支付处理失败：{ex.Message}",
                Data = null
            });
        }
    }

    /// <summary>
    /// 更新开单申请状态
    /// </summary>
    /// <param name="command">更新状态命令</param>
    /// <returns>更新结果</returns>
    [HttpPut("status")]
    [ProducesResponseType(typeof(APIResult<bool>), 200)]
    public async Task<ActionResult<APIResult<bool>>> UpdateOrderStatus(
        [FromBody] UpdateOrderStatusCommand command)
    {
        try
        {
            _logger.LogInformation("接收到更新开单申请状态请求，申请ID：{OrderApplicationId}，新状态：{Status}", 
                command.OrderApplicationId, command.Status);

            if (command == null)
            {
                _logger.LogWarning("更新状态命令为空");
                return Ok(new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "请求参数不能为空",
                    Data = false
                });
            }

            var result = await _mediator.Send(command);

            if (result.Code == APIEnum.OK)
            {
                _logger.LogInformation("开单申请状态更新成功，申请ID：{OrderApplicationId}，新状态：{Status}", 
                    command.OrderApplicationId, command.Status);
            }
            else
            {
                _logger.LogWarning("开单申请状态更新失败：{Message}", result.Message);
            }

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新开单申请状态时发生异常，申请ID：{OrderApplicationId}", command?.OrderApplicationId);
            
            return Ok(new APIResult<bool>
            {
                Code = APIEnum.Fail,
                Message = $"状态更新失败：{ex.Message}",
                Data = false
            });
        }
    }
}